<template>
    <div class="register">
        <div class="registerTitle" v-show="!isErr">
            <div class="text">注册</div>
        </div>
        <div class="from">
            <div class="errfrom" v-show="isErr">
                <div>
                    <i class="el-icon-error"></i>
                    <span class="errMsg">{{ errMsg }}</span>
                </div>
                <div>
                    <i class="el-icon-close close" @click="closeErrMsg"></i>
                </div>
            </div>
            <div class="form-item">
                <input
                    type="text"
                    name="username"
                    placeholder="邮箱"
                    v-model="registerForm.email"
                />
            </div>
            <div class="form-item" style="margin-bottom: 12px;">
                <input
                    type="password"
                    name="password"
                    placeholder="请输入密码"
                    v-model="registerForm.password"
                />
            </div>
            <div class="passwordTips">
                最少8位，至少包含一个大写字母，一个小写字母和一个数字
            </div>
            <div class="form-item">
                <input
                    type="password"
                    name="password"
                    placeholder="确认密码"
                    v-model="registerForm.secondPassword"
                />
            </div>
            <div class="form-item">
                <input
                    type="text"
                    name="username"
                    placeholder="请输入手机号"
                    v-model="registerForm.phone"
                />
            </div>
            <div class="phone-login-row">
                <div class="form-item-phone">
                    <input
                        type="text"
                        name="password"
                        placeholder="输入验证码"
                        v-model="registerForm.verificationCode"
                    />
                </div>
                <div
                    class="visBtn"
                    @click="get_register_code"
                    v-if="showGetCode"
                >
                    获取验证码
                </div>
                <div class="visBtn countTime" v-else>
                    <i class="el-icon-loading tranIcon"></i>{{ count }}
                </div>
            </div>
            <div class="meun">
                <div class="registerBtn" @click="registerUser">注册</div>
                <div class="greenTextBtn" @click="checkPageType('Login')">
                    使用已有账户登录
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { Base64 } from "js-base64";
import CryptoJS from "crypto-js";
import { getRegisterCode, toRegister } from "@/api/register";

export default {
    data() {
        return {
            isErr: false, //账户密码错误
            errMsg: "错误消息", //错误消息
            count: 0,
            timer: null,
            showGetCode: true, //获取验证码
            showSelectAreaCode: false, //显示手机区号选择
            registerForm: {
                email: "",
                password: "",
                secondPassword: "",
                phone: "",
                verificationCode: ""
            }
        };
    },
    methods: {
        checkPhone(phone) {
            if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone)) {
                return false;
            } else {
                return true;
            }
        },
        isEmailAvailable(emailInput) {
            // eslint-disable-next-line no-useless-escape
            var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
            if (!myreg.test(emailInput)) {
                return false;
            } else {
                return true;
            }
        },
        checkPageType(type) {
            this.$emit("checkPageType", type);
        },
        closeErrMsg() {
            this.isErr = false;
        },
        getDES(password) {
            //加密
            var key = "97498121231284655fsafasa"; //密钥
            var iv = "kfao5417";
            var encrypted = this.getDesString(password, key, iv); //密文
            return Base64.encode(encrypted);
        },
        getDesString(data, key, iv) {
            //加密
            console.log(window.crypto);
            var C_key = CryptoJS.enc.Utf8.parse(key);
            var C_iv = CryptoJS.enc.Utf8.parse(iv);
            var encrypted = CryptoJS.DES.encrypt(data, C_key, {
                iv: C_iv, //向量  偏移量
                mode: CryptoJS.mode.CBC, //加密模式
                padding: CryptoJS.pad.Pkcs7 //填充模式 补位
            });
            return encrypted.toString(); //返回的是base64格式密文
        },
        //成功倒计时
        countdown() {
            const TIME_COUNT = 60;
            if (!this.timer) {
                this.count = TIME_COUNT;
                this.showGetCode = false;
                this.timer = setInterval(() => {
                    if (this.count > 0 && this.count <= TIME_COUNT) {
                        this.count--;
                    } else {
                        this.showGetCode = true;
                        clearInterval(this.timer);
                        this.timer = null;
                    }
                }, 1000);
            }
        },
        get_register_code() {
            var phone = this.registerForm.phone.trim();
            var check = this.checkPhone(phone);
            if (!check) {
                this.errMsg = "请填写正确的手机号码";
                this.isErr = true;
                return;
            }
            this.getCodeTime();

            this.isErr = false;
        },
        //获取手机验证码
        async getCodeTime() {
            var getCodeData = await getRegisterCode({
                phone: this.registerForm.phone,
                code_type: "register_code"
            });
            console.log("获取", getCodeData);

            if (getCodeData.code === 200) {
                this.$message({
                    message: "已发送验证码",
                    customClass: "customClass",
                    type: "success"
                });
                this.countdown();
                setTimeout(() => {
                    this.isSend = false;
                }, 60000);
            } else {
                this.$message.error("验证码发送失败");
            }
        },
        //注册
        async registerUser() {
            var formMsg = {
                email: "邮箱",
                password: "密码",
                secondPassword: "确认密码",
                phone: "手机",
                verificationCode: "验证码"
            };
            var regform = this.registerForm;
            for (let key in regform) {
                if (regform[key].trim() == "") {
                    this.errMsg = `${formMsg[key]}不能为空`;
                    this.isErr = true;
                    return;
                }
                if (formMsg[key] == "手机") {
                    var phone = regform.phone.trim();
                    var check = this.checkPhone(phone);
                    if (!check) {
                        this.errMsg = "请填写正确的手机号码";
                        this.isErr = true;
                        return;
                    }
                }
            }
            if (!this.isEmailAvailable(regform.email.trim())) {
                this.errMsg = "请填写正确的邮箱";
                this.isErr = true;
                return;
            }
            if (
                /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/.test(
                    regform.password.trim()
                )
            ) {
                console.log("密码符合规定");
            } else {
                this.errMsg = "密码格式不正确";
                this.isErr = true;
                return;
            }
            if (regform.password.trim() != regform.secondPassword.trim()) {
                this.errMsg = "两次密码输入不一致";
                this.isErr = true;
                return;
            }
            this.isErr = false;

            //注册账号
            var password = this.getDES(regform.password);
            let reqObj = {
                phone: regform.phone,
                pwd: password,
                register_type: 1,
                register_code: regform.verificationCode
            };
            var toResData = await toRegister(reqObj);
            console.log("====================================");
            console.log(toResData);
            console.log("====================================");
            if (toResData.code === 200) {
                this.$store.commit(
                    "user/SETTING_RegisterSuccPhone",
                    regform.phone
                );
                this.checkPageType("RegisterSucc");
            } else {
                this.$alert(toResData.msg, "提示", {
                    confirmButtonText: "确定",
                    callback: () => {}
                });
            }
        }
    }
};
</script>

<style scoped lang="scss">
@import "./mixin.css";

/* 注册 */
.register {
    width: 400px;
    margin: 0 auto;
    margin-top: 42px;
    position: relative;

    .registerTitle {
        display: flex;
        font-size: 16px;
        line-height: 24px;
        color: #2d3440;
        text-align: center;

        .text {
            width: 80px;
            height: 22px;
            cursor: pointer;
            position: relative;
        }
    }
    .meun {
        display: flex;
        justify-content: space-between;
        height: 40px;
        line-height: 40px;
    }

    .registerBtn {
        width: 40%;
        height: 40px;
        text-align: center;
        font-size: 15px;
        color: #ffffff;
        background: #018854;
        border: 1px solid #dadfe6;
        border-radius: 20px;
        line-height: 40px;
        padding: 0 20px;
        box-sizing: border-box;
        cursor: pointer;

        &:hover {
            opacity: 0.8;
        }
    }
}
</style>
